What is Array
In JavaScript, an array is a data structure that allows you to store multiple values in a single variable. Arrays can hold a collection of any type of data, including numbers, strings, objects, or even other arrays (nested arrays).
Characteristics of Arrays:
Indexed: Each element in an array has a numeric index, starting from 0.
Dynamic: Arrays in JavaScript can grow or shrink in size and can hold elements of different data types.
Methods: Arrays come with built-in methods for adding, removing, and manipulating elements.
Creating an Arrays:
Using Array Literal:
const fruits = ["apple", "banana", "cherry"];
2. Using the new Array() Constructor:
const numbers = new Array(1, 2, 3, 4);
Accessing Array Elements
Each element in an array is assigned a numeric index, starting from 0. You can access an element using its index.
const colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: "red" (1st element)
console.log(colors[2]); // Output: "blue" (3rd element)
If you try to access an index that doesn’t exist, it returns undefined.
Why Use Arrays?
Organized Data: Arrays allow you to group related data into a single collection. Example: A list of students' names or a collection of scores.
Dynamic Storage: Arrays are flexible and can change in size or type of data. Example: You can add or remove elements as needed.
Efficient Access: Accessing elements by their index is very fast and straightforward.